package front_article_api

import (
	"blog_go/global"
	"blog_go/models"
	"blog_go/models/res"
	"blog_go/utils"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"time"
)

type ArticleCollReq struct {
	ArticleID uint `json:"article_id"`
}

// 文章收藏
func (ArticleApi) ArticleColl(c *gin.Context) {
	var req ArticleCollReq
	if err := c.ShouldBindJSON(&req); err != nil {
		logrus.Error(err)
		panic(err)
	}
	_claims := c.MustGet(utils.Claims)
	claims := _claims.(*utils.CustomClaims)
	var user2coll models.User2CollModel
	err := global.DB.First(&user2coll, "user_id = ? and article_id", claims.UserID, req.ArticleID).Error
	if err == nil {
		// 存在数据 则取消收藏
		global.DB.Delete(&user2coll)
		res.OkWithMessage("取消收藏", c)
		return
	}
	// 不存在数据 则去收藏
	global.DB.Create(&models.User2CollModel{
		UserID:    claims.UserID,
		ArticleID: req.ArticleID,
		CreatedAt: time.Now(),
	})
	res.OkWithMessage("收藏成功", c)
}
